package com.ja.rfid.service.impl;

import com.ja.rfid.config.CardConfigBean;
import com.ja.rfid.service.RfidService;
import com.ja.rfid.vo.CardVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: some desc
 * @author: hubin
 * @email: nightt0428@gmail.com
 * @date: 2022/9/1 12:14
 */
@Slf4j
@Service
public class RfidServiceImpl implements RfidService {

    @Autowired
    private CardConfigBean cardConfigBean;

    /**
     * 连接tcp，返回值0表示连接成功
     *
     * @param number
     * @return
     */
    @Override
    public Boolean doOpen(Integer number) {
        Boolean openFlag;
        Integer isOpen;
        String ipAddr;
        Integer cardPort;
        switch (number) {
            case 0:
                //191写卡机器
                CardVo writeCard = cardConfigBean.getWriteCard();
                ipAddr = writeCard.getIpAddr();
                cardPort = writeCard.getPort();
                try {
                    isOpen = writeCard.getCard().doOpen(ipAddr, cardPort);
                } catch (Exception e) {
                    log.error("写卡RFID机器({})打开异常:{}", ipAddr, e);
                    isOpen = -1;
                }
                openFlag = isOpen.equals(0);

                break;

            case 1:
                //192读卡机器

            case 2:
                //193读卡机器

            case 3:
                //194读卡机器
                List<CardVo> readCardList = cardConfigBean.getReadCardList();
                CardVo readCard = readCardList.get(number - 1);
                ipAddr = readCard.getIpAddr();
                cardPort = readCard.getPort();
                try {
                    isOpen = readCard.getCard().doOpen(ipAddr, cardPort);
                } catch (Exception e) {
                    log.error("读卡RFID机器({})打开异常:{}", ipAddr, e);
                    isOpen = -1;
                }
                openFlag = isOpen.equals(0);

                break;

            default:
                openFlag = false;
        }

        return openFlag;
    }

    /**
     * 关闭tcp，返回值0表示关闭连接成功
     *
     * @param number
     * @return
     */
    @Override
    public Boolean doClose(Integer number) {
        Boolean closeFlag;
        Integer isClose;
        String ipAddr;
        Integer cardPort;
        switch (number) {
            case 0:
                //191写卡机器
                CardVo writeCard = cardConfigBean.getWriteCard();
                ipAddr = writeCard.getIpAddr();
                cardPort = writeCard.getPort();
                try {
                    isClose = writeCard.getCard().doClose(cardPort);
                } catch (Exception e) {
                    log.error("写卡RFID机器({})关闭异常:{}", ipAddr, e);
                    isClose = -1;
                }
                closeFlag = isClose.equals(0);

                break;

            case 1:
                //192读卡机器

            case 2:
                //193读卡机器

            case 3:
                //194读卡机器
                List<CardVo> readCardList = cardConfigBean.getReadCardList();
                CardVo readCard = readCardList.get(number - 1);
                ipAddr = readCard.getIpAddr();
                cardPort = readCard.getPort();
                try {
                    isClose = readCard.getCard().doClose(cardPort);
                } catch (Exception e) {
                    log.error("读卡RFID机器({})关闭异常:{}", ipAddr, e);
                    isClose = -1;
                }
                closeFlag = isClose.equals(0);

                break;

            default:
                closeFlag = false;
        }

        return closeFlag;
    }

    /**
     * 查询标签数据
     *
     * @param number
     * @return
     */
    @Override
    public List<String> doQuery(Integer number) {
        List<String> queryData;
        switch (number) {
            case 0:
                //191写卡机器
                CardVo writeCard = cardConfigBean.getWriteCard();
                try {
                    String[] result = writeCard.getCard().doQuery();
                    queryData = (result == null || result.length == 0) ? new ArrayList<>()
                            : Arrays.asList(result).stream().distinct().collect(Collectors.toList());
                } catch (Exception e) {
                    log.error("写卡RFID机器({})查询标签数据异常:{}", writeCard.getIpAddr(), e);
                    queryData = new ArrayList<>();
                }

                break;

            case 1:
                //192读卡机器

            case 2:
                //193读卡机器

            case 3:
                //194读卡机器
                List<CardVo> readCardList = cardConfigBean.getReadCardList();
                CardVo readCard = readCardList.get(number - 1);
                try {
                    String[] result = readCard.getCard().doQuery();
                    queryData = (result == null || result.length == 0) ? new ArrayList<>()
                            : Arrays.asList(result).stream().distinct().collect(Collectors.toList());
                } catch (Exception e) {
                    log.error("读卡RFID机器({})查询标签数据异常:{}", readCard.getIpAddr(), e);
                    queryData = new ArrayList<>();
                }

                break;

            default:
                queryData = new ArrayList<>();
        }
        log.info("查询标签数据queryData:{}",queryData);

        return queryData;
    }

    /**
     * 批量查询标签数据,需要监听3s防止少读标签
     *
     * @param number
     * @return
     */
    @Override
    public List<String> doQueryBatch(Integer number) {
        List<String> queryData = new ArrayList<>();
        Boolean flag = false;
        //设置3秒的监听时间
        long timeStart = System.currentTimeMillis();
        while (!flag) {
            List<String> currentData = this.doQuery(number);
            queryData.addAll(currentData);

            long timeEnd = System.currentTimeMillis();
            flag = timeEnd >= timeStart + 3000;
        }
        return queryData.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 写卡流程（191写卡机器）
     *
     * @param oldEpc 旧的epc号，可以doQuery查询出来
     *               参数2 一体机的起始位置号，默认是2
     * @param newEpc 要修改的epc号，规定是8位
     *               参数4 一体机的密码，默认是00000000
     * @return
     */
    @Override
    public Boolean doWrite(String oldEpc, String newEpc) {
        CardVo writeCard = cardConfigBean.getWriteCard();
        Integer isWrite;
        try {
            isWrite = writeCard.getCard().doWrite(oldEpc, writeCard.getOrgAddr(), newEpc, writeCard.getPassWord());
        } catch (Exception e) {
            log.error("写卡RFID机器({})写入标签数据异常:{}", writeCard.getIpAddr(), e);
            isWrite = -1;
        }
        return isWrite.equals(0);
    }

}
